package com.coderising.kailuncen;

import java.lang.reflect.InvocationTargetException;
import java.util.Map;

public class Struts {

	private final static Configuration cfg = new Configuration("struts-kailuncen.xml");

	public Struts() {
	}

	public View runAction(String actionName, Map<String, String> params) {
		String className = cfg.getClassName(actionName);
		if (className == null) {
			return null;
		}

		try {
			Class<?> clz = Class.forName(className);
			Object action = clz.newInstance();
			ReflectionUtil.invokeSetMethods(action, params);
			String resultName = (String) clz.getDeclaredMethod("execute").invoke(action);
			Map<String, Object> result = ReflectionUtil.invokeGetMethods(action);
			String resultView = cfg.getViewResult(actionName, resultName);
			return new View(resultView, result);

		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (NoSuchMethodException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		}

		return null;
	}
}
